package com.onetoall.yjt;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import android.widget.Toast;

import com.onetoall.yjt.wxapi.PrefsAccessor;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONObject;

public class WXPayUtils {
	private PayReq req;
	private IWXAPI msgApi;
	private Context mContext;

	public WXPayUtils(Context context) {
		msgApi = WXAPIFactory.createWXAPI(context, null);
		mContext = context;
		req = new PayReq();
	}


	public void doPay(String jsonString) {
		try{
				String content = new String(jsonString);
				Log.e("get server pay params:",content);
				JSONObject json = new JSONObject(content);
				if(null != json && !json.has("retcode") ){
					PayReq req = new PayReq();
					//req.appId = "wxf8b4f85f3a794e77";
					// 测试用appId
					//订单参数
					req.appId           = json.getString("appid");
					req.partnerId       = json.getString("partnerid");
					req.prepayId        = json.getString("prepayid");
					req.nonceStr        = json.getString("noncestr");
					req.timeStamp       = json.getString("timestamp");
					req.packageValue    = json.getString("package");
					req.sign            = json.getString("sign");
					req.extData         = "app data"; // optional
					String order_id = json.getString("order_id");
					PrefsAccessor.getInstance(mContext).saveString("order_id",order_id);
					// 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
					msgApi.sendReq(req);


			}else{
				Log.d("PAY_GET", "服务器请求错误");
				Toast.makeText(mContext, "服务器请求错误", Toast.LENGTH_SHORT).show();
			}
		}catch(Exception e){
			Log.e("PAY_GET", "异常："+e.getMessage());
			Toast.makeText(mContext, "异常："+e.getMessage(), Toast.LENGTH_SHORT).show();
		}

	}



}
